package com.jd.after.modules.mis.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jd.after.common.core.F;
import com.jd.after.common.core.P;
import com.jd.after.common.core.R;
import com.jd.after.common.core.U;
import com.jd.after.modules.mis.entity.Blog;
import com.jd.after.modules.mis.entity.Blogimg;
import com.jd.after.modules.mis.service.BlogService;
import com.jd.after.modules.mis.service.BlogimgService;
import com.jd.after.modules.mis.service.CategoryService;
import com.jd.after.modules.sys.entity.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @RestController：返回json
 * 
 * @PostMapping
 * @GetMapping
 * 
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    // 注入
    @Autowired
    BlogService blogService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    BlogimgService blogimgService;

    /**
     * 列表 http://localhost:8081/blog/list?limit=5&page=1
     * 
     * @RequestParam=>map {k1:v1,k2:v2,k3:v3........}
     */
    @PostMapping("/list")
    public R list(@U User user, @RequestParam Map<String, Object> params) {
        // 分页参数
        // long curPage = 1;
        // long limit = 10;
        // if(params.get("page") != null){
        // curPage = Long.parseLong((String)params.get("page"));
        // }
        // if(params.get("limit") != null){
        // limit = Long.parseLong((String)params.get("limit"));
        // }
        // //分页对象
        // Page page = new Page(curPage, limit);
        System.out.println(params);

        // query=abc&pagenum=1&pagesize=5 *** select * from blog where title like
        // 'query' orderby created desc limit 1,5

        QueryWrapper<Blog> Q = new QueryWrapper<Blog>();

        String title = (String) params.get("title");
        String description = (String) params.get("description");
        String cId = (String) params.get("cId");

        if (title != null && !title.isEmpty())
            Q.like("title", title);

        if (description != null && !description.isEmpty())
            Q.like("description", description);

        // 怎么搜索子目录下
        if (cId != null && !cId.isEmpty())
            Q.eq("c_id", cId);

        IPage<Blog> pageData = blogService.page(P.page(params), Q.orderByDesc("created"));

        // 拿到 分类 {{scope.row.centity.cname}}
        for (Blog blog : pageData.getRecords()) {
            blog.setCentity(categoryService.getById(blog.getcId()));

        }

        return R.ok(pageData);
    }

    /**
     * 信息
     * 
     * /info/3 ==>get
     * 
     * @PathVariable
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        Blog blog = blogService.getById(id);
        blog.setBlogmulimglist(blogimgService.list(new QueryWrapper<Blogimg>().eq("blog_id", blog.getId())));
        return R.ok(blog);
    }

    /**
     * 保存 http://localhost:8081/blog/save
     * 
     * "Content-Type": "application/json"
     * 
     * @RequestBody
     */
    @PostMapping("/save")
    public R save(@U User user, MultipartFile file, MultipartFile[] filelist, String blog) {
        // 1.保存大图图片
        String fpath = "upload/blog/";
        String blogimg = F.saveFile(file, fpath);

        // 2.保存多图图片
        List<Blogimg> blogmultimg = new ArrayList<>();
        for (MultipartFile f : filelist) {
            Blogimg bm1 = new Blogimg();
            bm1.setImgpath(F.saveFile(f, fpath));
            blogmultimg.add(bm1);
        }

        // 3.保存业务实体
        Blog entity = JSONObject.parseObject(blog, Blog.class);

        entity.setUserId(user.getId());
        entity.setCreated(LocalDateTime.now());
        entity.setStatus(0);
        entity.setImg(blogimg); // 大图
        entity.setBlogmulimglist(blogmultimg);

        blogService.saveBlogAndImg(entity);

        return R.ok();
    }

    /**
     * 修改   ,待完善？？？？？？？？？？？？？？？，更新图片和多图数据
     */
    @PostMapping("/update")
    public R update(@Validated @RequestBody Blog blog) {
        blogService.updateById(blog);
        return R.ok();
    }

    /**
     * 删除 [4,7,100,99] ==>ids
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids) {

        for (Long id : ids) {
            // 1.先删大图图片
            String rpath = blogService.getById(id).getImg(); // 先找数据库存的图片路径
            F.deleteFile(rpath); // 删掉图片

            // 2.再删多图图片
            List<Blogimg> list = blogimgService.list(new QueryWrapper<Blogimg>().eq("blog_id", id));
            if (list != null && list.size() > 0) {
                for (Blogimg b : list) {
                    F.deleteFile(b.getImgpath());
                }
            }

        }

        // 3.再删业务数据
        System.out.println(ids);
        blogService.deleteBlogAndImg(ids);
        return R.ok();
    }

    /**
     * 按月统计博客数量，多参数  API 定义 参数接
     */
    @PostMapping("/tjBlogNum")
    public R tjBlogNum(@RequestParam Map<String, Object> params) {
        List<Map<String, Object>> result = blogService.tjBlogNum(params);

        return R.ok();
    }

}
